package model

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"strings"
	"time"
)

/*
type GormList []string

	func (g GormList) Value() (driver.Value, error) {
		// 如何将[]string转成json字符串存到数据库中
		return json.Marshal(g)
	}

	func (g *GormList) Scan(input interface{}) error {
		// 将数据库中的数据转换为[]string
		return json.Unmarshal(input.([]byte), g)
	}
*/
type GormList []string

func (g GormList) Value() (driver.Value, error) {
	return json.Marshal(g)
}

func (g *GormList) Scan(input interface{}) error {
	var data []string

	// 处理可能的空值
	if input == nil {
		*g = []string{}
		return nil
	}

	// 尝试将输入转换为[]byte
	var inputBytes []byte
	switch v := input.(type) {
	case []byte:
		inputBytes = v
	case string:
		inputBytes = []byte(v)
	default:
		return fmt.Errorf("unsupported Scan type for GormList: %T", input)
	}

	// 如果输入是空字符串，返回空列表
	if len(inputBytes) == 0 {
		*g = []string{}
		return nil
	}

	// 检查是否是JSON格式
	if inputBytes[0] == '[' && inputBytes[len(inputBytes)-1] == ']' {
		// 是JSON数组，正常解析
		if err := json.Unmarshal(inputBytes, &data); err != nil {
			return err
		}
	} else {
		// 不是JSON数组，按逗号分隔
		str := string(inputBytes)
		data = strings.Split(str, ",")
		// 去除每个元素的首尾空格
		for i := range data {
			data[i] = strings.TrimSpace(data[i])
		}
	}

	*g = GormList(data)
	return nil
}

type BaseModel struct {
	ID        int32          `gorm:"primary_key;type:int" json:"id"`
	CreatedAt time.Time      `gorm:"column:add_time" json:"-"`
	UpdatedAt time.Time      `gorm:"column:update_time" json:"-"`
	DeletedAt gorm.DeletedAt `json:"-"`
	IsDeleted bool           `gorm:"column:is_delete" json:"-"`
}
